<template>
  <div v-loading="loading">
    <BasicForm @register="registerForm" @value-change="handleFormChange" >
      <template #complexityRules="{ model, field, schema }">
         <a-checkbox-group v-model:value="model[field]" style="width: 100%" class="mt-1">
          <a-row>
            <a-col :span="24" v-for="(item) in schema.componentProps.options" :key="item.value">
              <a-checkbox :value="item.value">{{item.label}}</a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </template>
      <template #validatePassword="{ model, field, schema }">
        <a-input allowClear v-model:value="validatePassword" placeholder="请输入待检测密码" />
      </template>
      <template #passwordLength="{ model, field }">
        <a-form-item-rest>
          <div class="flex">
             <a-input-number 
              size="middle" class="mr-5" 
              v-model:value="model['minLength']" 
              :maxlength="50" addon-before="最小长度" 
            />
             <a-input-number 
              size="middle" 
              v-model:value="model['maxLength']" 
              :maxlength="50" 
              addon-before="最大长度" 
            />
          </div>
        </a-form-item-rest>
      </template>

      <template #footer-action="{ model, field }">
        <a-button class="mr-5">重置</a-button>
        <a-button type="primary" @click="handleSubmit">保存</a-button>
      </template>
    </BasicForm>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, watch, onMounted, nextTick } from "vue"
  import { Radio, Switch } from "ant-design-vue";
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { ConfigKeyEnum } from "/@/enums/configKeyEnum";
  import * as configApis from '/@/api/infra/config'
  import * as securityApis from '/@/api/iam/security'
  import { formSchema } from "./data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { debounce } from "lodash"

  import { useAppStore } from "/@/store/modules/app"

  const { createMessage } = useMessage()

  const validatePassword = ref()
  const isUpdate = ref(false)
  const record = ref({})
  const emit = defineEmits(["register"])

  const preData = ref()
  const loading = ref(false)
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: formSchema,
    labelWidth: 135,
    compact: true,
    wrapperCol: { span: 24 },
    showActionButtonGroup: false,
    // layout: "vertical"
  })

  onMounted(async () => {
    try {
      loading.value = true
      const data = await configApis.getConfigByKey(ConfigKeyEnum.PASSWORD_POLICY)
      data.fields.complexityRules = data?.fields?.complexityRules.map(e => e.checkType)

      record.value = data?.fields || {}
      isUpdate.value = !!data
      await setFieldsValue(record.value)
    } finally {
      loading.value = false
    }
  })

  const handleValidatePassword = debounce(async (e) => {
    const key = 'password'
    createMessage.loading({
      content: `检测中...`,
      key,
      duration: 0,
    })
    const result = await securityApis.validatePassword(e)
    if (result.success) {
      createMessage.success('校验成功')
    } else {
      createMessage.warn(result.msg)
    }
    createMessage.destroy(key)
  }, 1000) //防抖1s

  watch(
    () => validatePassword.value,
    async (val) => {
      try {
        if (val) {
          await handleValidatePassword({ password: val })
        }
      } catch (err) {
        console.error(err)
      }
    }
  )

  const handleFormChange = (data) => {
    if (JSON.stringify(preData.value) == JSON.stringify(data)) {
      return
    }
    preData.value = data
    useAppStore().setPageDataSaveFlag(false)
  }

  async function handleSubmit(showLoading = true) {
    loading.value = !showLoading ? loading.value : true
    try {
      let values = await validate()
      delete values["footer-action"]
      const formValues = {
        ...values,
        complexityRules: values.complexityRules.split(',').map(type => {
          return { checkType: type }
        }),
        configKey: ConfigKeyEnum.PASSWORD_POLICY
      }

      console.log("formValues", formValues)
      await securityApis.savePasswordPolicy(formValues)
      showLoading && createMessage.success("保存成功")
      useAppStore().setPageDataSaveFlag(true)
    } catch(e : any) {
      console.error(e)
      const errMsg = e.errorFields ? e.errorFields?.flatMap(e => e.errors).join('、') : e.msg
      console.error('errMsg', errMsg)
      createMessage.warn(errMsg || '保存失败，请联系管理员')
    } finally {
      loading.value = !showLoading ? loading.value : false
    }
  }
</script>

<style lang="less">

.ant-form-item {
  margin-right: 10px !important;
}

.ant-input-number-group-addon {
  font-size: 13px !important;
}

.app-card {
  display: flex;
  align-items: center;
  align-content: center;
  border-radius: 10px;
  margin-right: 14px;
  margin-bottom: 14px;
  margin: 0 auto; 

  .app-logo {
    width: 64px;
    // height: 45px;
    padding-left: 24px;
  }

  .app-name {
    flex: 1 1;
    max-width: 138px;
    padding-left: 8px;
    white-space: normal;
    text-overflow: ellipsis;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
}

</style>
